package com.woniuxy.config;

import com.woniuxy.core.service.OrderRunService;
import com.woniuxy.entity.DTO.GrabEvent;
import com.woniuxy.entity.OrderRun;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.nio.channels.Channel;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RunListener {
    @Autowired
    private OrderRunService orderRunService;
    @Autowired
    private StringRedisTemplate redisTemplate;
//    @RabbitListener(queues = "runQueue")
//    public void runConsumption(String msg){
//        System.out.println("msg:"+msg);
//    }
    @RabbitListener(queues = "runQueue1")
    public void handleGrabEvent(GrabEvent event,  @Header(AmqpHeaders.MESSAGE_ID) String msgId) {

        // 1. 幂等检查（防止重复消费）
        if (redisTemplate.opsForValue().get("grab:msg:" + msgId) != null) {
            return;
        }

        try {
            // 2. 创建订单（本地事务）
            orderRunService.createOrder(event);

            // 3. 记录消息消费
            redisTemplate.opsForValue().set("grab:msg:" + msgId, "PROCESSED", 2, TimeUnit.HOURS);
            //4.删除库存
            redisTemplate.delete("stock:"+event.getTaskId());
        } catch (Exception e) {
            // 4. 失败重试（记录异常）
            log.error("抢单处理失败 task:{}, user:{}", event.getTaskId(), event.getUserId(), e);
            throw new AmqpRejectAndDontRequeueException(e);
        }
    }
}
